/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.index;

import com.inspur.edp.lcm.metadata.api.entity.MetadataPackage;
import com.inspur.edp.lcm.metadata.core.entity.MdProjDependencySource;
import com.inspur.edp.lcm.metadata.core.entity.MdProjectDependencyNode;
import com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MetadataPackageIndexServiceForDB extends MetadataPackageIndexService {
    private static MetadataPackageIndexServiceForDB instance;

    private final CustomizationRtServerService customizationRtServerService = SpringBeanUtils.getBean(CustomizationRtServerService.class);

    public static MetadataPackageIndexServiceForDB getInstance() {
        if (instance == null) {
            instance = new MetadataPackageIndexServiceForDB();
        }
        return instance;
    }

    /**
     * 根据元数据工程路径以及元数据工程信息（可不传）构造元数据工程对应依赖引用节点
     *
     * @param metadataPackageName 元数据包名
     * @return 元数据工程对应依赖引用节点
     */
    public MdProjectDependencyNode getMetadataDependencyNode(String metadataPackageName) {
        MdProjectDependencyNode dependencyNode = new MdProjectDependencyNode();
        dependencyNode.setMetadataPackageName(metadataPackageName);
        dependencyNode.setSourceName(MdProjDependencySource.DataBase);
        // 读取依赖信息
        MetadataPackage metadataPackage = customizationRtServerService.findMetadataPackageByName(metadataPackageName);
        if (metadataPackage == null) {
            return null;
        }

        // 获取元数据包引用
        // 所有元数据包引用视为数据库元数据包引用
        Set<String> metadataRefsInMdPkg = getMetadataRefsInMdPkg(metadataPackage);

        // 补充数据库数据包引用
        Set<String> mdpkgRefsInMdPkg = getMdpkgRefsInMdPkg(metadataPackage);
        mdpkgRefsInMdPkg.addAll(metadataRefsInMdPkg);
        dependencyNode.setMdpkgRefs(mdpkgRefsInMdPkg);

        // 补充IDP元数据引用
        Set<String> idpMetadataIds = getIdpMdIdsInMdPkg(metadataPackage);
        dependencyNode.setIdpMetadataIds(idpMetadataIds);

        List<String> metadataIds = getMetadataIdsInMdPkg(metadataPackage);
        dependencyNode.setMetadataIds(metadataIds);

        return dependencyNode;
    }
}
